﻿using Serilog;
using System.Net;
using System.Net.Mail;
using System.Text;
using WorldmeServer.Models.Base;
using WorldmeServer.Models.配置相关;

namespace WorldmeServer.Utils
{
    public class EmailUtils
    {
        /// <summary>
        /// 发送邮件到指定邮箱  自定义主题和内容
        /// </summary>
        /// <param name="toEmail">收件人邮箱</param>
        /// <param name="subject">主题</param>
        /// <param name="body">内容</param>
        public static void SendEmail(string toEmail,string subject,string body)
        {
            // 创建一个 MailMessage 对象
            MailMessage mail = new MailMessage(ConfigUtils.EmailConfig.Email, toEmail);

            // 设置 SMTP 服务器信息
            SmtpClient smtpClient = new SmtpClient("smtp.163.com", 25);

            // 设置邮箱主题和内容
            mail.Subject = subject;
            mail.Body = body;

            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = new NetworkCredential(ConfigUtils.EmailConfig.Email, ConfigUtils.EmailConfig.Password);

            try
            {
                // 发送邮件
                smtpClient.Send(mail);
                Log.Information("发送邮件:{toEmail}", toEmail);
            }
            catch (Exception ex)
            {
                Log.Error("邮件发送失败：{Error}", ex.Message);
            }
        }


        public static void SendEmail(string toEmail,string templateName,Dictionary<string,object> args)
        {
            // 创建一个 MailMessage 对象
            MailMessage mail = new MailMessage(ConfigUtils.EmailConfig.Email, toEmail);

            // 设置 SMTP 服务器信息
            SmtpClient smtpClient = new SmtpClient("smtp.163.com", 25);

            // 根据模板名称获取消息模板
            bool success = ConfigUtils.Templates.TryGetValue(templateName, out Template template);
            if (!success || template == null)
            {
                throw new Exception("消息模板不存在");
            }
            StringBuilder subject = new StringBuilder(template.Subject);
            StringBuilder body = new StringBuilder(template.Body);

            // 将参数设置到消息模板中
            foreach (var arg in args)
            {
                subject.Replace($"$[{arg.Key}]",arg.Value.ToString());
                body.Replace($"$[{arg.Key}]", arg.Value.ToString());
            }

            // 设置邮箱主题和内容
            mail.Subject = subject.ToString();
            mail.Body = body.ToString();

            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = new NetworkCredential(ConfigUtils.EmailConfig.Email, ConfigUtils.EmailConfig.Password);

            try
            {
                // 发送邮件
                smtpClient.Send(mail);
                Log.Information("发送邮件:{toEmail}", toEmail);
            }
            catch (Exception ex)
            {
                Log.Error("邮件发送失败：{Error}", ex.Message);
            }
        }

    }
}
